package com.example.demo.controller;

import com.example.demo.pojo.DeviceData;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/device")
@Slf4j
public class IttaController {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping(value = "/data", produces = "application/json;charset=UTF-8")
    public ResponseEntity<?> receiveData(@RequestBody String rawData) {
        try {
            // 记录原始请求数据
            log.info("接收到的原始数据: {}", rawData);

            // 尝试解析JSON
            DeviceData deviceData = objectMapper.readValue(rawData, DeviceData.class);

            // 记录解析后的数据
            log.info("解析后的设备数据: {}", deviceData);

            // 业务逻辑处理
            if ("state".equals(deviceData.getType())) {
                log.info("状态更新 - 标识符: {}, 状态: {}",
                        deviceData.getIdentifier(),
                        deviceData.getData() != null ? deviceData.getData().get("status") : null);
                return ResponseEntity.ok().body(deviceData);
            }

            return ResponseEntity.ok().body(deviceData);

        } catch (Exception e) {
            log.error("处理请求时发生错误: ", e);
            return ResponseEntity.badRequest().body("处理请求时发生错误: " + e.getMessage());
        }
    }

    @PostMapping(value = "/property", produces = "application/json;charset=UTF-8")
    public ResponseEntity<?> receivePropertyData(@RequestBody String rawData) {
        try {
            // 记录原始请求数据
            log.info("接收到的属性数据: {}", rawData);

            // 只需输出原始数据，返回成功响应
            return ResponseEntity.ok().body("数据接收成功");

        } catch (Exception e) {
            log.error("处理属性请求时发生错误: ", e);
            return ResponseEntity.badRequest().body("处理请求时发生错误: " + e.getMessage());
        }
    }
}